package com.whut.whw.personalinfo.mywant;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.model.BackResult;
import com.whut.whw.model.Goods;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.EmptyUtils;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.RecyclerViewUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.MYGOODS_PAGESIZE;
import static com.whut.whw.constant.ConfigConsts.WANTGOODS_URL;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/24
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class MyWantActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.rv_mywant_list)
    RecyclerView mRvMywantList;

    @BindView(R.id.srl_want_refresh)
    SwipeRefreshLayout mySwipeRefreshLayout;

    private static final String TAG = "MyWantActivity";

    private final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

    private MyWantRecyclerViewAdapter myAdapter;

    // 是否正在上拉加载
    private boolean isLoading;

    private String yhbh;
    private int currentPage = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mywant;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initToolbar();
        initSwipeRefresh();
        initMRvMywantList();
    }

    /**
     * 初始化toolbar
     */
    private void initToolbar() {
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);
        toolbar.setTitle(R.string.mywant_title);
    }

    /**
     * 初始化下拉刷新控件
     */
    private void initSwipeRefresh() {
        mySwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
    }

    /**
     * 初始化recyclerView控件
     */
    private void initMRvMywantList() {

        //获取用户编号
        SharedPreferences sp = getSharedPreferences("userinfo", MODE_APPEND);
        yhbh = sp.getString("yhbh", "");

        //初始设置适配器
        mRvMywantList.setLayoutManager(linearLayoutManager);
        List<Goods> mList = new ArrayList<>();
        myAdapter = new MyWantRecyclerViewAdapter(context, mList);
        mRvMywantList.setAdapter(myAdapter);
    }

    @Override
    public void setListener() {
        // toolbar返回按钮
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //下拉刷新
        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadingData(true, 1);
            }
        });

        //每项的点击事件以及删除事件
        myAdapter.setmIDeleteBtnClickListener(new MyWantRecyclerViewAdapter.IonSlidingViewClickListener() {
            @Override
            public void onItemClick(View view, int position) {//每项点击事件的数据
                ToastUtils.showShort(myAdapter.getmDatas().get(position).toString());
            }

            @Override
            public void onDeleteBtnCilck(View view, int position) {//删除
                myAdapter.removeData(position);//移除此项
                loadingCheck(mRvMywantList);

            }
        });

        // 上拉加载
        mRvMywantList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("TC----", RecyclerViewUtils.isVisBottom(recyclerView) + "---" + recyclerView.getScrollState());
                loadingCheck(recyclerView);
            }
        });
    }

    /**
     * 上拉刷新验证
     */
    private void loadingCheck(RecyclerView recyclerView) {
        //判断是否正在加载在底部
        if (RecyclerViewUtils.isVisBottom(recyclerView)) {
            //验证是否在下拉刷新
            boolean isRefreshing = mySwipeRefreshLayout.isRefreshing();
            if (isRefreshing) {// SwipeRefreshLayout正在刷新
                myAdapter.notifyItemRemoved(myAdapter.getItemCount());
                return;
            }
            //判断是否加载完成，isLoading为true则表示加载完成已经到底了，false未到底
            if (!isLoading) {
                isLoading = true;
                loadingData(false, currentPage);
            }
        }
    }

    /**
     * 数据刷新操作
     *
     * @param loadingFlag true为下拉刷新、false为上拉刷新
     * @param pageNum
     */
    private void loadingData(final boolean loadingFlag, int pageNum) {
        if (EmptyUtils.isNotEmpty(yhbh)) {
            currentPage = pageNum;
            OkHttpUtils
                    .post()
                    .url(WANTGOODS_URL)
                    .addParams("yhbh", yhbh)
                    .addParams("currentPage", "" + currentPage)
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            getUiDelegate().toastLong(e.toString());
                            Log.e("TC", e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.e("TC", response.isSuccess() + "--" + response.getData());
                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    isNoLoading(true);
                                } else {
                                    isNoLoading(false);
                                }
                                if (loadingFlag) {
                                    myAdapter.updateData(list);
                                } else {
                                    myAdapter.appendData(list);
                                }
                                currentPage++;//页面+1
                            } else {//如果下拉刷新没有数据
                                isNoLoading(true);
                                if (loadingFlag) {
                                    myAdapter.updateData(new ArrayList<Goods>());
                                }
                            }
                            mySwipeRefreshLayout.setRefreshing(false);
                            myAdapter.notifyDataSetChanged();
                        }
                    });
        } else {
            Log.e("TC", "yhbh errror");
        }
    }

    /**
     * 刷新操作时候判断下拉刷新状态和显示
     *
     * @param flag
     */
    private void isNoLoading(boolean flag) {
        isLoading = flag;
        myAdapter.setFooterFlag(flag);
    }
}
